package com.example.translateappjava.Activity.HomeFragmentActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.translateappjava.DataBase.UserInfo;
import com.example.translateappjava.R;
import com.example.translateappjava.Service.CalculateRalate.Calculate;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.*;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;

import java.util.ArrayList;

public class CalculatorActivity extends AppCompatActivity {
    private TextView perName, perAge, perHeight, perWeight, perGender, perSportLevel;
    private Button btnSlideDown;
    private ViewAnimator viewAnimator;
    private Calculate calculate = new Calculate();
    private double bmiValue;
    private double bfpValue;
    private double bmrValue;
    private double tdeeValue;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_calculator);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        viewAnimator = findViewById(R.id.viewAnimator);
        btnSlideDown = findViewById(R.id.btn_slide_down);
        perName = findViewById(R.id.view_name);
        perAge = findViewById(R.id.view_age);
        perHeight = findViewById(R.id.view_height);
        perWeight = findViewById(R.id.view_weight);
        perGender = findViewById(R.id.view_gender);
        perSportLevel = findViewById(R.id.view_sport);
        LinearLayout tdeeLayout = findViewById(R.id.layout_tdee);

        UserInfo currentUserInfo = UserInfo.getsUserInfo();
        if (currentUserInfo != null) {
            // 使用当前用户信息来填充表单字段
            perName.setText(currentUserInfo.getName());
            perAge.setText(Integer.toString(currentUserInfo.getAge()));
            perHeight.setText(currentUserInfo.getHeight());
            perWeight.setText(currentUserInfo.getWeight());
            perGender.setText(currentUserInfo.getSex());
            perSportLevel.setText(currentUserInfo.getSportLevel());
        }

        findViewById(R.id.btn_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 为下滑按钮设置点击监听器
        // 为下滑按钮设置点击监听器
        btnSlideDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查输入字段是否为空或无效
                if (isInputValid()) {
                    // 切换到下一个视图
                    viewAnimator.showNext();

                    TextView bmiResult = findViewById(R.id.bodyMassIndex);
                    TextView bfpResult = findViewById(R.id.bodyFatPercentage);
                    TextView bmrResult = findViewById(R.id.basalMetabolicRate);
                    TextView tdeeResult = findViewById(R.id.totalDailyEnergyExpenditure);
                    // Try to parse the input values and calculate results
                    try {
                        double weight = Double.parseDouble(perWeight.getText().toString());
                        double height = Double.parseDouble(perHeight.getText().toString());
                        int age = Integer.parseInt(perAge.getText().toString());
                        boolean isMale = perGender.getText().toString().equals("男");
                        int sportLevel = Integer.parseInt(perSportLevel.getText().toString());

                        bmiValue =  Double.parseDouble(calculate.bodyMassIndex(weight, height));
                        bfpValue = Double.parseDouble(calculate.bodyFatPercentage(weight, height, age, isMale));
                        bmrValue = Double.parseDouble(calculate.basalMetabolicRate(weight, height, age, isMale));
                        tdeeValue = Double.parseDouble(calculate.totalDailyEnergyExpenditure(weight, height, age, isMale, sportLevel));

                        // Format the results to two decimal places and add units
                        String bmiFormatted = String.format("%.2f kg/m²",bmiValue);
                        String bfpFormatted = String.format("%.2f%%", bfpValue);
                        String bmrFormatted = String.format("%.2f kcal/day", bmrValue);
                        String tdeeFormatted = String.format("%.2f kcal/day", tdeeValue);

                        // Set the formatted text to the TextViews
                        bmiResult.setText(bmiFormatted);
                        bfpResult.setText(bfpFormatted);
                        bmrResult.setText(bmrFormatted);
                        tdeeResult.setText(tdeeFormatted);

                        // BMI仪表盘
                        PieChart chartBMI = findViewById(R.id.chart_bmi);
                        // 设置仪表盘数据
                        setBMIData(chartBMI, (float) bmiValue); // 假设bmiValue是您计算出的BMI值

                        // BFP饼图
                        PieChart chartBFP = findViewById(R.id.chart_bfp);
                        // 设置饼图数据
                        setBFPData(chartBFP, (float) bfpValue); // 假设bfpValue是您计算出的BFP值

                        // BMR条形图
                        BarChart chartBMR = findViewById(R.id.chart_bmr);
                        // 设置条形图数据
                        setBMRData(chartBMR, (float) bmrValue); // 假设bmrValue是用户的BMR值，averageBMR是平均BMR值

                        // TDEE食物图标
                        ImageView imageTDEE = findViewById(R.id.image_tdee);
                        // 设置TDEE图标
                        // 在您的活动中调用此方法
                        System.out.println(tdeeLayout);
                        setTDEEImage(tdeeLayout, (float) tdeeValue);// 假设tdeeValue是您计算出的TDEE值

                    } catch (NumberFormatException e) {
                        // Handle the exception if parsing fails
                        Toast.makeText(CalculatorActivity.this, "输入格式错误，请确保所有字段都是数字。", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // 如果输入无效，显示错误消息或禁用按钮
                    Toast.makeText(CalculatorActivity.this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    // 检查输入是否有效的方法
    private boolean isInputValid() {
        return !perName.getText().toString().trim().isEmpty() &&
                !perAge.getText().toString().trim().isEmpty() &&
                !perHeight.getText().toString().trim().isEmpty() &&
                !perWeight.getText().toString().trim().isEmpty() &&
                !perGender.getText().toString().trim().isEmpty() &&
                !perSportLevel.getText().toString().trim().isEmpty() &&
                isNumeric(perAge.getText().toString().trim()) &&
                isNumeric(perHeight.getText().toString().trim()) &&
                isNumeric(perWeight.getText().toString().trim()) &&
                isNumeric(perSportLevel.getText().toString().trim());
    }

    // 检查字符串是否为有效数字的方法
    private boolean isNumeric(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    // 设置BMI仪表盘数据的方法
    private void setBMIData(PieChart chart, float bmiValue) {
        // 创建数据集
        ArrayList<PieEntry> entries = new ArrayList<>();

        // 假设这些是BMI分类的边界值
        float normalBMIUpperBound = 24.9f;
        float overweightBMIUpperBound = 29.9f;

        // 根据BMI值设置不同的颜色
        int colorGreen = Color.parseColor("#388E3C"); // 正常
        int colorYellow = Color.parseColor("#FBC02D"); // 超重
        int colorRed = Color.parseColor("#D32F2F"); // 肥胖

        // 添加BMI值
        entries.add(new PieEntry(bmiValue, "当前BMI"));

        // 添加正常范围的值
        if (bmiValue <= normalBMIUpperBound) {
            entries.add(new PieEntry(normalBMIUpperBound - bmiValue, "正常范围"));
        }

        // 添加超重范围的值
        if (bmiValue > normalBMIUpperBound && bmiValue <= overweightBMIUpperBound) {
            entries.add(new PieEntry(overweightBMIUpperBound - bmiValue, "超重范围"));
        }

        // 添加肥胖范围的值
        if (bmiValue > overweightBMIUpperBound) {
            entries.add(new PieEntry(bmiValue - overweightBMIUpperBound, "肥胖范围"));
        }

        PieDataSet dataSet = new PieDataSet(entries, "BMI分类");
        // 根据BMI值设置颜色
        ArrayList<Integer> colors = new ArrayList<>();
        for (PieEntry entry : entries) {
            if (entry.getLabel().equals("当前BMI")) {
                // 根据BMI值选择颜色
                if (bmiValue <= normalBMIUpperBound) {
                    colors.add(colorGreen);
                } else if (bmiValue <= overweightBMIUpperBound) {
                    colors.add(colorYellow);
                } else {
                    colors.add(colorRed);
                }
            } else {
                // 其他部分使用透明颜色
                colors.add(Color.parseColor("#00FFFFFF"));
            }
        }

        dataSet.setColors(colors);
        dataSet.setValueTextSize(12f);
        dataSet.setValueTextColor(Color.BLACK);

        PieData data = new PieData(dataSet);
        chart.setData(data);
        chart.invalidate(); // 刷新图表
    }


    // 设置BFP饼图数据的方法
    private void setBFPData(PieChart chart, float bfpValue) {
        // 创建数据集
        ArrayList<PieEntry> entries = new ArrayList<>();

        // 假设这些是体脂率分类的百分比
        float essentialFat = 10f; // 必需的体脂
        float athleteFat = 15f; // 运动员的体脂
        float fitnessFat = 20f; // 健康的体脂
        float overFat = 25f; // 过高的体脂

        // 添加体脂率值
        entries.add(new PieEntry(bfpValue, "当前"));

        // 添加其他分类的值
        entries.add(new PieEntry(essentialFat, "必需"));
        entries.add(new PieEntry(athleteFat - essentialFat, "运动员-必需"));
        entries.add(new PieEntry(fitnessFat - athleteFat, "健康-运动员"));
        entries.add(new PieEntry(overFat - fitnessFat, "过高-健康"));
        entries.add(new PieEntry(75-bfpValue, "剩余占比"));
        // 根据分类设置颜色
        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(Color.parseColor("#F44336")); // 当前体脂
        colors.add(Color.parseColor("#4CAF50")); // 必需的体脂
        colors.add(Color.parseColor("#FFEB3B")); // 运动员的体脂
        colors.add(Color.parseColor("#2196F3")); // 健康的体脂
        colors.add(Color.parseColor("#9C27B0")); // 过高的体脂
        colors.add(Color.parseColor("#EFFFFF")); // 过高的体脂

        PieDataSet dataSet = new PieDataSet(entries, "体脂分类");
        dataSet.setColors(colors);
        dataSet.setValueTextSize(10f);
        dataSet.setValueTextColor(Color.BLACK);

        PieData data = new PieData(dataSet);
        chart.setData(data);
        chart.invalidate(); // 刷新图表
    }


    // 设置BMR条形图数据的方法
    private void setBMRData(BarChart chart, float bmrValue) {
        // 创建数据集
        ArrayList<BarEntry> entries = new ArrayList<>();
        entries.add(new BarEntry(0f, bmrValue, "用户BMR"));
        entries.add(new BarEntry(1f, 1600f, "男性平均BMR"));
        entries.add(new BarEntry(2f, 1200f, "女性平均BMR"));
        entries.add(new BarEntry(3f, 1800f * 1.1f, "青少年BMR")); // 假设青少年BMR为成年人的110%
        entries.add(new BarEntry(4f, 1600f * 0.9f, "老年人BMR")); // 假设老年人BMR为成年人的90%

        BarDataSet dataSet = new BarDataSet(entries, "BMR对比");
        dataSet.setColors(new int[] {Color.parseColor("#FF5722"), Color.parseColor("#3F51B5"), Color.parseColor("#E91E63"), Color.parseColor("#8BC34A"), Color.parseColor("#FFEB3B")});
        dataSet.setValueTextSize(12f);
        dataSet.setValueTextColor(Color.BLACK);

        BarData data = new BarData(dataSet);
        chart.setData(data);

        // 添加描述文本
        Description description = new Description();
        description.setText("基础代谢率 (BMR) 对比");
        description.setTextSize(10f);
        chart.setDescription(description);

        // 确保X轴标签正确显示
        chart.getXAxis().setDrawLabels(true);
        chart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(new String[]{"用户", "男性", "女性", "青少年", "老年"}));

        // 设置X轴标签的显示位置
//        chart.getDescription().setPosition(chart.getXAxis().getPosition());

        chart.getAxisLeft().setDrawLabels(true); // 显示左侧Y轴标签
        chart.getLegend().setEnabled(true); // 显示图例
        chart.invalidate(); // 刷新图表
    }



    // 设置TDEE食物图标的方法
    private void setTDEEImage(LinearLayout layout, float tdeeValue) {
        // 计算等效的奶茶杯数
        int milkTeaCups = (int) (tdeeValue / 400); // 假设一杯奶茶是400千卡

        // 清除旧的图标
        layout.removeAllViews();
        System.out.println(milkTeaCups);
        // 根据奶茶杯数添加图标
        for (int i = 0; i < milkTeaCups; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ice_latte); // 假设您有奶茶杯的图标资源
            layout.addView(imageView);

            // 设置图标的布局参数
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            layoutParams.setMargins(0, 0, 0, 0); // 设置边距
            imageView.setLayoutParams(layoutParams);
        }
    }
}